

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:xim/common/get_style_view.dart';
import 'package:xim/common/util/datetime.dart';
import 'package:xim/common/util/system.dart';
import 'package:xim/config/route_config.dart';
import 'package:xim/http/apis/session/session_model.dart';
import 'package:xim/widget/common/state.dart';
import 'package:badges/badges.dart' as badges;

class ChatListStyle extends Style with AppBarMixin {

  @override
  String get appBarTitle => "Xim";

  /// 消息列表间分割线的高度
  final double messageDividerHeight = 1;

  /// 消息列表的高度
  final double messageItemHeight = 62;

  /// 消息列表的padding
  final EdgeInsets messageEdgeInsets = const EdgeInsets.symmetric(vertical: 6, horizontal: 8);

  @override
  List<Widget> get appBarActions => [
    PopupMenuButton(
      offset: const Offset(0, 60),
      icon: const Icon(Icons.add_circle_outline),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      itemBuilder: (BuildContext context) {
        return [
          PopupMenuItem(
            child: IconActionBottom(
              onPressed: (){
                Routers.back();
                Routers.toCreateSessionPage();
              },
              icon: Icon(Icons.chat_outlined, color: textColor.color,),
              label: const Text("发起群聊",),
            ),
          ),
          PopupMenuItem(
            child: IconActionBottom(
              onPressed: (){
                Routers.back();
                Routers.toFriendAddPage();
              },
              icon: const Icon(Icons.person_add_alt_outlined,),
              label: const Text("添加朋友",),
            ),
          ),
          PopupMenuItem(
            child: IconActionBottom(
              onPressed: (){
                Routers.back();
                Routers.toScanPage();
              },
              icon: const Icon(Icons.document_scanner_outlined,),
              label: const Text("扫一扫",),
            ),
          ),
        ];
      },
    ),
  ];

  /// 展示最近的一条信息
  Widget previewSessionMessage(SessionMessageModel sessionMessage,{String Function(SessionMessageModel sessionMessage)? msgFunc}){
    msgFunc ??= _defaultChatMsg;
    return sessionMessage.latestMessage != null?
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            msgFunc.call(sessionMessage),
            style: TextStyle(fontSize: 12, color:weakTextColor.color),
            overflow: TextOverflow.ellipsis,
          ),
          if (sessionMessage.unReadCount > 0)
            badges.Badge(
              badgeContent: Text(
                sessionMessage.unReadCount.toString(),
                style: const TextStyle(fontSize: 9, color: Colors.white),
              ),
            )
        ],
      ) : const SizedBox();
  }

  /// 用户信息
  Widget userInfoRow(SessionMessageModel sessionMessage, {String Function(DateTime dateTime)? dataFormat}){
    dataFormat ??= _defaultDateFormat;
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          sessionMessage.name,
          style: TextStyle(fontSize: 16, color: textColor.color),
        ),
        if (sessionMessage.latestMessage != null)
          Text(
            dataFormat(sessionMessage.latestMessage!.sendTime,),
            style: TextStyle(fontSize: 12, color: weakTextColor.color),
          )
        else  const SizedBox()
      ],
    );
  }

  String _defaultDateFormat(DateTime dateTime) {
    var nowDateTime = DateTime.now();
    var days = nowDateTime.day - dateTime.day;
    var month = nowDateTime.month - dateTime.month;
    var year = nowDateTime.year - dateTime.year;

    if (year > 0) {
      // 跨年
      return dateTime.format("yyyy年M月d日");
    }
    if (month > 0) {
      // 跨月
      return dateTime.format("M月d日");
    }
    if (days > 0) {
      // 跨天
      return dateTime.format("M月d日");
    }
    return dateTime.format("HH:mm");
  }

  String _defaultChatMsg(SessionMessageModel sessionMessage, {int len = 30}) {
    return "${sessionMessage.latestMessage!.userInfo.name}: "
        "${sessionMessage.latestMessage!.content}".ellipsis(len);
  }

  /// 设置应用密码弹窗组件
  Widget userPasswordDialog(void Function() onTab, void Function() onClose){
    return  GestureDetector(
      onTap: onTab,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8,vertical: 4),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(4),
            border: Border.all(color: Colors.amber)
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Row(
              children: [
                Icon(Icons.warning_amber, size: 14,),
                SizedBox(width: 6,),
                Text(
                  "为了账号安全，请尽快设置应用密码",
                  style: TextStyle(fontSize: 14),
                ),
              ],
            ),
            InkWell(
              onTap: ()=>onClose.call(),
              child: const Icon(Icons.close, size: 14,)
            )
          ],
        ),
      ),
    );
  }

}

class IconActionBottom extends StatelessWidget {
  const IconActionBottom({Key? key, required this.icon, required this.label, this.onPressed}) : super(key: key);
  final Icon icon;
  final Text label;
  final void Function()? onPressed;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () => onPressed?.call(),
      child: Row(
        children: [
          icon,
          const SizedBox(width: 8,),
          label
        ],
      ),
    );
  }

}